package com.ryan.dispatcher.comp.touch;

import com.ryan.ohos.extension.event.DispatchHelper;
import com.ryan.ohos.extension.event.impl.ViewGroupHelper;
import com.ryan.ohos.extension.event.interfaces.ViewGroup;
import ohos.agp.components.AttrSet;
import ohos.agp.components.Component;
import ohos.agp.components.DirectionalLayout;
import ohos.app.Context;
import ohos.multimodalinput.event.TouchEvent;

public class ViewParent extends DirectionalLayout implements Component.TouchEventListener, ViewGroup {

    private ViewGroupHelper impl;

    private float lastY, originY;
    private long downTime;

    public ViewParent(Context context) {
        super(context);
        init();
    }

    public ViewParent(Context context, AttrSet attrSet) {
        super(context, attrSet);
        init();
    }

    public ViewParent(Context context, AttrSet attrSet, String styleName) {
        super(context, attrSet, styleName);
        init();
    }

    private void init() {
        impl = new ViewGroupHelper(this);
        setTouchEventListener(this);
    }

    @Override
    public boolean onTouchEvent(Component component, TouchEvent event) {
        return DispatchHelper.dispatch(component, event);
    }

    @Override
    public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
        impl.requestDisallowInterceptTouchEvent(disallowIntercept);
    }

    @Override
    public boolean onInterceptTouchEvent(TouchEvent ev) {
        float y = ev.getPointerScreenPosition(ev.getIndex()).getY();
        switch (ev.getAction()) {
            case TouchEvent.PRIMARY_POINT_DOWN:
                lastY = y;
                originY = getComponentAt(0).getContentPositionY();
                break;

            case TouchEvent.POINT_MOVE:
                lastY = y;
                break;
        }

        if (ev.getAction() == TouchEvent.PRIMARY_POINT_DOWN) {
            downTime = System.currentTimeMillis();
        } else {
            return System.currentTimeMillis() - downTime > 1000;
        }
        return false;
    }

    @Override
    public boolean dispatchTouchEvent(TouchEvent event) {
        return impl.dispatchTouchEvent(event);
    }

    @Override
    public boolean onTouchEvent(TouchEvent event) {
        float y = event.getPointerScreenPosition(event.getIndex()).getY();
        switch (event.getAction()) {
            case TouchEvent.PRIMARY_POINT_DOWN:
                lastY  = y;
                originY = getComponentAt(0).getContentPositionY();
                break;

            case TouchEvent.POINT_MOVE:
                float diff = y - lastY;
                getComponentAt(0).setContentPositionY(originY + diff);
                break;
        }
        return true;
    }

    @Override
    public boolean isConsumed() {
        return impl.isConsumed();
    }
}
